require( '$d/css/common.less' );
require( './style.less' );
define( [
  'jquery',
  'require',
  'header',
  'message',
  'imgCategory',
  'api',
  'pagination',
  'blocksit',
  'picture_browser',
  'bootstrap',
  'bigwe_utils',
  'login',
  'constants',
  'behavior',
  'searchMaterial'
], function( $, require ) {

  var ShowTitleMessage = require( 'message' ),
    showTime = ShowTitleMessage.showTime,
    bu = require( 'bigwe_utils' ),
    BIGWE_API = require( 'api' ),
    getUrlParam = bu.getUrlParam,
    pb = require( 'picture_browser' ),
    c = require( 'constants' ),
    login = require( 'login' );

  var searchMaterial = require( 'searchMaterial' );

  var behavior = require( 'behavior' );
  var pictureClassify = require( 'imgCategory' ).pictureClassify;
  //点击到相应的页面
  //$( '.search_area .search_item' ).eq( 2 ).addClass( 'selected' ).siblings().removeClass( 'selected' );
  searchMaterial.addClassByIndex( 2 );
  var more_flag = 1;
  $( '.up_left .item' ).click( function() {
    if ( $( this ).hasClass( 'current' ) ) {
      var _idx = $( this ).index();
      $( this ).removeClass( 'current' );
      $( '.up_filter div' ).eq( _idx ).slideUp();
    } else {
      var _idx = $( this ).index();
      $( this ).addClass( 'current' ).siblings().removeClass( 'current' );
      $( '.up_filter div' ).eq( _idx ).slideDown().siblings().slideUp();
    }
  } );

  //图片分类
  var fenlei_html = '';
  for ( var i in pictureClassify ) {
    fenlei_html += '<span _value="' + i + '">' + pictureClassify[ i ] + '</span>'
  }
  $( '.fenlei_up' ).empty().append( '<span class="green">全部</span>' + fenlei_html );

  var search_type = 'image',
    search_key = getUrlParam( 'search_key' ),
    isOk = true;
  search_key = search_key || '';
  var image_url = [];
  if ( search_key != '' ) {
    var state = {
      search_type: search_type,
      search_key: search_key,
    };
    history.replaceState( state, document.title, '/search/images?search_key=' + search_key + '' );
  }
  //搜索接口
  // var _search_total_pages = null,
  var isLoading = 0,
    isNoData = 0;
  var _search = {
    options: {
      key: decodeURI( search_key ),
      type: search_type,
      p: 1,
      l: 20,
    },
    init: function() {
      this.result_list();
      this.other_search();
      this._filter();
    },
    result_list: function( _parameter ) {
      var html_list = '',
        source_icon = '',
        _this = this;
      //image_url = [];
      isLoading = 1;
      _this.firstDataLoaded && $( '.spinner' ).show();
      $.ajax( {
        type: "post",
        dataType: "json",
        url: BIGWE_API.SEARCH.SEARCH_LIST,
        data: this.options,
        success: function( data ) {
          if ( data.data.total_rows == 0 ) {
            //ShowTitleMessage.showWarning( '暂无数据', showTime );
            $( 'body' ).css( {
              'overflow': 'hidden',
              'padding-right': 17
            } );
            $( '.search_piclist' ).append( '<p class="no_content"><span class="glyphicon glyphicon-flash"></span>暂无内容</p>' );
            $( '.search_main .up_right .green' ).text( 0 );
            return;
          }
          if ( data.ret == 0 ) {
            var _parameter = data.data.data;
            var totalNumber = data.data.total_rows;
            $( 'body' ).prop( 'style', '' );
            // 图片列表
            for ( var i in _parameter ) {
              var pic_data = _parameter[ i ];
              var imgUrl = pic_data.img_url;

              if ( pic_data.height && imgUrl.indexOf( 'forwallpaper' ) == -1 && pic_data.height / pic_data.width <= 2.4 ) {
                pic_data.image_id = pic_data.cd;
                image_url.push( pic_data );
                var _title = ( pic_data.title == "" || pic_data.title == undefined || pic_data.title == null ) ? '' : pic_data.title;
                var participle = data.data.words;
                if ( _title ) {
                  if ( participle.length == 0 ) {
                    search_wz = $( '.search_ipt' ).val();
                    if ( search_wz != '' ) {
                      _title = _title.replace( new RegExp( bu.regExpReplace( search_wz ), "g" ), '<strong>' + search_wz + '</strong>' );
                    }
                  } else {
                    for ( var j in participle ) {
                      _title = _title.replace( new RegExp( bu.regExpReplace( participle[ j ] ), "g" ), '<strong>' + participle[ j ] + '</strong>' );
                    }
                  }
                }
                var html_p = ( pic_data.title == '' || !pic_data.title ) ? '<p style="display:none"></p>' : '<p>' + _title + '</p>';

                var _ratio = pic_data.width / pic_data.height,
                  height_inst = 232 / _ratio,
                  bg_num = Math.ceil( 5 * Math.random() );
                html_list += '<div class="pic_item bg_color' + bg_num + '" pictureview-event>' +
                  '<img src="' + c.surpportHostName + '/timthumb.php?w=232&src=' + pic_data.img_url + '" height="' + height_inst + '" onerror="this.src=\'' + c.resPath + '/images/wuyulantu.png\'">' +
                  '<div class="shade">' +
                  html_p +
                  '<div class="icon_btn clearfix" cd="' + pic_data.cd + '">' +
                  '<span dz_or_collect class="iconfont icon-dianzan ' + ( pic_data.is_like == 1 ? 'golden' : '' ) + '" data-toggle="tooltip" title="点赞"></span>' +
                  '<span dz_or_collect class="iconfont icon-collect ' + ( pic_data.is_collect == 1 ? 'golden' : '' ) + '" data-toggle="tooltip" title="收藏"></span>' +
                  '<a class="iconfont icon-fasong" data-toggle="tooltip" title="分发" href="/sending?pic_cd=' + pic_data.cd + '" target="_blank"></a>' +
                  '<span class="iconfont icon-fenxiang" data-toggle="tooltip" title="分享" imglianj="' + pic_data.img_url + '">' +
                  '<div class="share">' +
                  '<a title="分享到QQ空间" class="qzone" href="javascript:void(0);"></a>' +
                  // '<a title="分享到微信" class="weixin" href="javascript:void(0);"></a>'+
                  '<a title="分享到新浪微博" class="sina" href="javascript:void(0);"></a>' +
                  '</div>' +
                  '</span>' +
                  '</div>' +
                  '</div>' +
                  '</div>'
              }

            }
            if ( _parameter.length == 0 ) {
              isNoData = 1;
              ShowTitleMessage.showWarning( '没有数据了', showTime );
              //$( '.search_piclist' ).empty().append( '<p class="no_content"><span class="glyphicon glyphicon-flash"></span>暂无内容</p>' );
            } else {
              var current_page = _this.options.p;
              _this.firstDataLoaded && $( '.search_piclist' ).append( html_list ).BlocksIt( 'reload' );
              isImgLoad( current_page );

              // isImgLoad(function(){
              // 	$( '.search_piclist' ).BlocksIt( 'reload' );
              // 	$('.search_piclist img').slice((current_page-1)*20).each(function(){
              // 		$(this).parent('.pic_item').addClass('animate')
              // 	});
              // },current_page);

            }

            $( '.search_main .up_right .green' ).text( totalNumber );

          } else {
            ShowTitleMessage.showWarning( '请输入搜索内容', showTime );
          }

          _this.firstDataLoaded = true;
        },
        complete: function() {
          $( '.search_piclist .pic_item' ).css( 'opacity', '1' );
          $( '.spinner' ).hide();
          isLoading = 0;
        }
      } );
    },
    _filter: function() {
      var _this = this;
      $( '.fenlei_up' ).on( 'click', 'span', function() {
        $( this ).addClass( 'green' ).siblings().removeClass( 'green' );
        $( '.up_left .item:first-child' ).text( $( this ).text() )
        _this.options.cc = $( this ).attr( '_value' );
        _this.options.p = 1;
        isOk = true;
        isNoData = 0;
        $( '.search_piclist' ).empty();
        image_url = [];
        _this.result_list();
      } );
      $( '.pic_size_up' ).on( 'click', 'span', function() {
        $( this ).addClass( 'green' ).siblings().removeClass( 'green' );
        $( '.custom input[type=text]' ).val( '' )
        $( '.up_left .item:last-child' ).text( $( this ).text() )
        _this.options.width = $( this ).data( 'width' );
        _this.options.height = $( this ).data( 'height' );
        _this.options.p = 1;
        isOk = true;
        isNoData = 0;
        $( '.search_piclist' ).empty();
        image_url = [];
        _this.result_list();
      } );
      var custom_search = false;
      $( '.custom' ).on( 'click', 'input[type=button]', function() {
        var w = $( '.custom .custom_width' ).val();
        var h = $( '.custom .custom_height' ).val();
        if ( w == '' && h == '' ) {
          $( '.custom. custom_width' ).focus();
          return false;
        } else {
          custom_search = true;
        }
        // $( '.custom input[type=text]' ).each( function() {
        //   if ( $( this ).val() == '' || parseInt( $( this ).val() ) == 0 ) {
        //     $( this ).val( '' );
        //     $( this ).focus();
        //     custom_search = false;
        //     return false;
        //   } else {
        //     custom_search = true;
        //   }
        // } );
        if ( custom_search ) {
          var up_t = ( w != '' && h != '' ) ? ( w + '*' + h ) : ( w || h );
          $( '.pic_size_up span' ).removeClass( 'green' );
          $( '.up_left .item:last-child' ).text( up_t )
          _this.options.width = $( '.custom_width' ).val();
          _this.options.height = $( '.custom_height' ).val();
          _this.options.p = 1;
          isNoData = 0;
          isOk = true;
          $( '.search_piclist' ).empty();
          image_url = [];
          _this.result_list();
        }

      } );
    },
    other_search: function() {
      //无刷新替地址
      var _this = this;
      /*$( '.home_search_ipt button' ).click( function( e ) {

      } );*/
      searchMaterial.onSearch = function( search_key_in ) {
        search_type = 'image';
        search_key = search_key_in;
        if ( search_key != '' ) {
          _this.options.key = search_key;
          _this.options.type = search_type
          _this.options.p = 1;
          isOk = true;
          $( '.search_piclist' ).empty();
          isNoData = 0;
          image_url = [];
          _this.result_list();
          var state = {
            search_type: search_type,
            search_key: search_key,
          };
          // sherlockl 运营数据统计
          behavior.addRecord( {
            category: behavior.searchImg,
            action: search_key
          } );
          history.replaceState( state, document.title, '/search/images?search_key=' + search_key + '' );
        } else {
          location.href = '/search/images';
        }

      }
      // 这里为什么要再绑定事件呢？?并且也没有清空当前结果 2017年8月1日 Sherlockl 

      /* $( '.home_search_ipt .search_ipt' ).bind( 'keypress', function( event ) {
        search_type = 'image';
        search_key = $( '.home_search_ipt .search_ipt' ).val();
        if ( event.keyCode == "13" ) {
          if ( $( '.search_ipt' ).val() != '' ) {
            event.stopImmediatePropagation();
            event.preventDefault();
            _this.options.key = search_key;
            _this.options.type = search_type
            _this.options.p = 1;
            isOk = true;
            isNoData = 0;
            image_url = [];
            _this.result_list();
            var state = {
              search_type: search_type,
              search_key: search_key,
            };
            history.replaceState( state, document.title, '/search/images?search_key=' + search_key + '' );
          }
        }
      } ); */
      //$( '.home_search_ipt .search_ipt' ).val( decodeURI( search_key ) );
      searchMaterial.setInputVal( decodeURI( search_key ), true );
      window.addEventListener( 'popstate', function( e ) {
        if ( history.state ) {
          var state = e.state;
          _this.options.key = state.search_key;
          _this.options.type = state.search_type
          _this.options.p = 1;
          isOk = true;
          isNoData = 0;
          image_url = [];
          _this.result_list();
          $( '.home_search_ipt .search_ipt' ).val( decodeURI( state.search_key ) );
        } else {
          window.location.reload();
        }
      }, false );
    },

  }
  _search.init();
  $( function() {
    $( '.search_piclist' ).BlocksIt( {
      numOfCol: 5,
      offsetX: 5,
      offsetY: 5
    } );
  } );

  var t_img; // 定时器
  var isLoad = true; // 控制变量
  // 判断图片加载的函数
  function isImgLoad( pages ) {
    _start = ( pages - 1 ) * 10;

    $( '.search_piclist img' ).slice( _start ).each( function() {
      if ( $( this )[ 0 ].complete == true ) {
        $( this ).parent( '.pic_item' ).removeClass( 'bg_color1 bg_color2 bg_color3 bg_color4 bg_color5' );
      }
      if ( $( this )[ 0 ].complete == false ) {
        isLoad = false;
        return false;
      }
    } );

    if ( isLoad ) {
      clearTimeout( t_img );
      //callback();
    } else {
      isLoad = true;
      t_img = setTimeout( function() {
        isImgLoad( pages );
      }, 500 );
    }
  }
  //筛选固定
  var $ele = $( '.search_main' ),
    _top = $( '.upper', $ele ).offset().top;
  $( window ).on( 'scroll', function() {
    var _scrollTop = $( document ).scrollTop();
    $( '.up_left .item' ).removeClass( 'current' );
    $( '.up_filter>div' ).slideUp( 'slow' );
    if ( _scrollTop > _top ) {
      $( '.upper', $ele ).css( {
        'position': 'fixed',
        'top': 0,
        'left': '50%',
        'margin-left': -600,
        'z-index': 100
      } );
      $ele.addClass( 'pt64' );
      $( '.icon-iconfonttop', $ele ).fadeIn();
    } else {
      $( '.upper', $ele ).css( {
        'position': 'static',
        'top': 0,
        'left': 0,
        'margin-left': 0,
        'z-index': 100
      } );
      $ele.removeClass( 'pt64' );
      $( '.icon-iconfonttop', $ele ).fadeOut();
    }

  } );
  $( '.icon-iconfonttop', $ele ).click( function() {
    $( 'body' ).animate( {
      scrollTop: 0
    } );
  } );
  //数据加载
  bu.scrollMaxWin( function() {
    if ( !isLoading && !isNoData ) {
      _search.options.p++;
      _search.result_list();
    }

  } );
  //自定义筛选
  $( '.custom' ).on( 'keydown', 'input[type=text]', function( e ) {
    if ( !( e.keyCode == 8 || ( e.keyCode >= 48 && e.keyCode <= 57 ) || ( e.keyCode >= 96 && e.keyCode <= 105 ) ) ) {
      event.returnValue = false;
    }
    // if(e.keyCode<8||(e.keyCode>8&&e.keyCode<48)||e.keyCode>57){
    // 	event.returnValue=false;
    // }
  } );
  /*点赞--收藏*/
  $( document ).on( 'click', '[dz_or_collect]', function( e ) {
    e.stopPropagation();
    var _class = $( this ).hasClass( 'golden' );
    //var count = $(this).find('.count');
    var icon = $( this );
    var cd = $( this ).parent().attr( 'cd' );

    var h = $( this ).parents( '.pic_item' ).index();
    if ( !_class ) {
      //$(this).addClass('golden'); 
      //count.text(parseInt(count.text()) + 1);
      //$.tipsBox({obj: $(this)});
      if ( icon.hasClass( 'icon-collect' ) ) {
        var collect_text = '收藏成功'
        collect_img();
      } else {
        var marked = '点赞成功';
        like_img();
      }
    } else {
      //$(this).removeClass('golden');
      //$.tipsBox({obj: $(this),str: '-1'});
      //count.text(parseInt(count.text()) - 1);
      if ( icon.hasClass( 'icon-collect' ) ) {
        var collect_text = '已取消收藏'
        collect_img();
      } else {
        var marked = '已取消点赞';
        like_img();
      }
    }

    function like_img() {
      $.ajax( {
        type: 'post',
        url: BIGWE_API.IMG_BROWSE.DO_LIKE_IMG,
        data: {
          cd: cd
        },
        success: function( data ) {
          var data = eval( '(' + data + ')' )
          if ( data.ret == 0 ) {
            ShowTitleMessage.show( marked, showTime );
            image_url[ h ].is_like = data.data.is_like;
            if ( data.data.is_like == 1 ) {
              $( '.pic_item' ).eq( h ).find( '.icon-dianzan' ).addClass( 'golden' );
            } else {
              $( '.pic_item' ).eq( h ).find( '.icon-dianzan' ).removeClass( 'golden' );
            }

          } else {
            ShowTitleMessage.showWarning( data.msg, showTime );

          }
        }
      } )
    }

    function collect_img() {
      $.ajax( {
        type: 'post',
        url: BIGWE_API.IMG_BROWSE.DO_COLLECT_IMG,
        data: {
          cd: cd
        },
        success: function( data ) {
          var data = eval( '(' + data + ')' )
          if ( data.ret == 0 ) {
            ShowTitleMessage.show( collect_text, showTime );
            image_url[ h ].is_collect = data.data.is_collect;
            if ( data.data.is_collect == 1 ) {
              $( '.pic_item' ).eq( h ).find( '.icon-collect' ).addClass( 'golden' );
            } else {
              $( '.pic_item' ).eq( h ).find( '.icon-collect' ).removeClass( 'golden' );
            }
          } else {
            ShowTitleMessage.showWarning( data.msg, showTime );
          }
        }
      } )
    }
  } );

  //分享
  $( '.search_piclist' ).on( 'click', '.pic_item .icon-fenxiang', function( e ) {
    e.stopPropagation();
  } );
  var timer = null;
  $( '.search_piclist' ).on( 'mouseenter', '.pic_item .icon-fenxiang', function() {
    $( this ).find( '.share' ).fadeIn();
    $( this ).parents( '.pic_item' ).siblings().find( '.share' ).fadeOut();
    clearTimeout( timer );
  } );
  $( '.search_piclist' ).on( 'mouseleave', '.pic_item .icon-fenxiang', function() {
    var icon_index = $( this ).parents( '.pic_item' ).index();
    timer = setTimeout( function() {
      $( '.search_piclist .pic_item' ).eq( icon_index ).find( '.share' ).fadeOut();
    }, 350 );

  } );
  var a, b, s, t = 0;
  s = {
    title: '',
  }, t = {
    jiathis: function( a, b ) {
      window.open( "http://www.jiathis.com/send/?webid=" + a + "&url=" + encodeURIComponent( b.url ) + "&summary=" + encodeURIComponent( b.summary ) + "&uid=2118247&pic=" + encodeURIComponent( b.img ) + "&appkey=" + b.appkey );
    }
  }, $( ".search_piclist" ).on( 'click', '.share a', function( a ) {
    var user_login = $( '#user_login' ).val();
    if ( user_login == '' ) {
      a.preventDefault();
      a.stopImmediatePropagation();
      $( '#login-modal' ).modal( 'show' );
      login.loginSuccessAndContinue = $.proxy( function() {
        $( this ).trigger( 'click' );
      }, this );

    } else {
      var _url = 'http://' + window.location.host + '/search/img_detail?picxx_cd=' + $( this ).parents( '.icon_btn' ).attr( 'cd' );
      a.stopPropagation();
      s.img = $( this ).parents( '.icon-fenxiang' ).attr( 'imglianj' );
      s.url = _url;
      s.summary = $( this ).parents( '.icon_btn' ).siblings( 'p' ).text() == '' ? '分享图片' : $( this ).parents( '.icon_btn' ).siblings( 'p' ).text();
      share( a.target.className );
      a.preventDefault();
    }
  } );

  function share( c ) {
    switch ( c ) {
      case "qzone":
        s.appkey = 101286682;
        t.jiathis( "qzone", s );
        break;
      case "sina":
        s.appkey = 2121870539;
        t.jiathis( "tsina", s );
        break;
        // case "weixin":
        //     createRcode("weixin", s);
        //     break;
    }
  }

  //分发
  $( '.search_piclist' ).on( 'click', '.pic_item .icon-fasong', function( e ) {
    var user_login = $( '#user_login' ).val();
    e.stopImmediatePropagation();
    if ( user_login == '' ) {
      e.preventDefault();
      $( '#login-modal' ).modal( 'show' );
      login.loginSuccessAndContinue = $.proxy( function() {
        //location.href = $(this).prop('href');
        window.open( $( this ).prop( 'href' ), 'sending' );
      }, this );

    }
  } );
  //点击预览
  // var pageNo = 1,
  // 	isNoData = false;
  // pb.preparation = function( $pic, direction ) {
  // 	// 页码对象 
  // 	ShowTitleMessage.show( '正在加载' );
  // 	isNoData = false;
  // 	var options = {
  // 		key: decodeURI( search_key ),
  // 		type: search_type,
  // 		p: 1,
  // 		l: 20,
  // 	}

  // 	if ( !isNoData ) {
  // 		direction > 0 ? ++pageNo : --pageNo;
  // 		pb.pageEvent = function( pageEvent ) {
  // 			pageEvent == 1 ? ++pageNo : --pageNo;
  // 		}
  // 		if ( pageNo > _search_total_pages ) {
  // 			pageNo = _search_total_pages;
  // 			isNoData = true;
  // 		} else {
  // 			if ( pageNo > 50 ) {
  // 				options.p = 50;
  // 				isNoData = true;
  // 			} else if ( pageNo < 1 ) {
  // 				isNoData = true;
  // 				pageNo = 1;
  // 			} else {
  // 				options.p = pageNo;
  // 			}
  // 		}
  // 	}
  // 	return isNoData ? 0 : $.ajax( {
  // 		type: 'post',
  // 		dataType: 'json',
  // 		url: BIGWE_API.SEARCH.SEARCH_LIST,
  // 		data: options,
  // 		success: function( data ) {
  // 			var _data = data.data.data,
  // 				img_arr = [];
  // 			for ( var i in _data ) {
  // 				_data[ i ].image_id = _data[ i ].cd;
  // 				img_arr.push( _data[ i ] );
  // 			}
  // 			pb.doPreviewPicture( img_arr, direction );

  // 		},
  // 		complete: function() {
  // 			ShowTitleMessage.hide();
  // 		}
  // 	} );
  // }
  $( document ).on( 'click', '[pictureview-event]', function() {
    pb.doPreviewPicture( image_url, undefined, $( this ).index() );
    // pageNo = _search.options.p;
    // isNoData = 0;
  } );
} )
